package database

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	"tyjt-ferry/database/orm"
	"tyjt-ferry/pkg/logger"
)

type MysqlIOC struct {
	DbType   string
	Host     string
	Port     int
	Name     string
	Username string
	Password string
}

func NewMysqlIOC(DbType string, Host string, Port int, Name string, Username string, Password string) *MysqlIOC {
	return &MysqlIOC{
		DbType:   DbType,
		Host:     Host,
		Port:     Port,
		Name:     Name,
		Username: Username,
		Password: Password,
	}
}

func (e *MysqlIOC) Open(dbType string, conn string) (db *gorm.DB, err error) {
	return gorm.Open(dbType, conn)
}

// 把MySQL的链接信息，组装成一个string返回
func (e *MysqlIOC) GetConnect() string {
	// username:password@tcp(host:port)/databasename?charset=utf8&parseTime=True&loc=Local&timeout=10000ms
	conn := fmt.Sprintf("%s:%s@tcp(%s:%v)/%s?charset=utf8&parseTime=True&loc=Local&timeout=10000ms",
		e.Username, e.Password, e.Host, e.Port, e.Name)
	return conn
}

func (e *MysqlIOC) Setup() {
	// todo 为什么必须要先定义一个err
	var err error
	orm.MysqlConn = e.GetConnect()
	fmt.Println(orm.MysqlConn)
	orm.Eloquent, err = e.Open(e.DbType, orm.MysqlConn)
	if err != nil {
		logger.Errorf("%s connect error %v", e.DbType, err)
	} else {
		logger.Infof("%s connect success ", e.DbType)
	}

	if orm.Eloquent.Error != nil {
		logger.Fatalf("database error %v", orm.Eloquent.Error)
	}

	orm.Eloquent.LogMode(viper.GetBool("settings.gorm.logMode"))
	orm.Eloquent.DB().SetMaxOpenConns(viper.GetInt("settings.gorm.maxOpenConn"))
	orm.Eloquent.DB().SetMaxIdleConns(viper.GetInt("settings.gorm.maxIdleConn"))

}
